package com.youjiang.meeting.controller;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang.StringUtils;

import com.youjiang.meeting.po.UserInfo;
import com.youjiang.meeting.utils.GetHttpSessionConfigurator;

/**
 * <p>
 * Title: ManagerSendInformaction
 * </p> 
 * <p>
 * Description:TODO
 * </p> 
 * <p>
 * Company: YouJiang
 * </p> 
 *
 * @author feng
 * @date 2016年12月9日 下午9:39:07
 * @version 1.0
 */
@ServerEndpoint(value="/manageation",configurator=GetHttpSessionConfigurator.class)
public class ManagerSendInformaction {
	private Session session;
	private HttpSession httpSession;
	
	private static Set<ManagerSendInformaction> informationSocket;
	static{
		informationSocket=new HashSet<ManagerSendInformaction>();
	}
	@OnOpen
	public void onOpen(Session session,EndpointConfig config) {
		HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        System.out.println( httpSession.getAttribute("userInfo"));
        UserInfo info = (UserInfo) httpSession.getAttribute("userInfo");
        if(info!=null){
        	this.session = session;
            this.httpSession = httpSession;
            System.out.println("------------有人接进来了");
    		try {
    			synchronized (informationSocket) {
    				informationSocket.add(this);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
        }else{
        	if(session!=null){
        		try {
					session.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        }
	}
	@OnMessage
	public  void receive(Session  session,String msg ){
		send(msg);
	}
	
	@OnClose
	public void onClose(Session session){
		synchronized (informationSocket) {
		   informationSocket.remove(this);	
		}
	}
	
	@OnError
	public void error(Throwable t){
		System.out.println(t);
	}
	public static void send(String info) {
		if(!StringUtils.isEmpty(info)){
			synchronized (informationSocket) {
				for(ManagerSendInformaction it:informationSocket){
					try{
						it.getSession().getBasicRemote().sendText(info);
					}catch(Exception e){
						e.printStackTrace();
						System.out.println("Chat Error: Failed to send message to client");
						
					}
					
				}
			}
		}
		
	}
	
	
	public Session getSession() {
		return session;
	}
}
